package com.cancer.biz.auth.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.web.session.mgt.WebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cancer.biz.auth.entity.User;
import com.cancer.biz.auth.entity.query.UserQuery;
import com.cancer.biz.auth.entity.query.UserQuery.Criteria;
import com.cancer.biz.auth.mapper.UserDao;
import com.cancer.biz.auth.service.UserService;
import com.cancer.biz.common.exception.DataException;
import com.cancer.biz.common.exception.ParameterEmptyException;
import com.cancer.common.Il8nUtil;
import com.cancer.common.util.ExceptionUtil;
import com.cancer.common.web.PageBean;
import com.cancer.common.web.PagingContext;

/**
 * @Company GeekPlus
 * @TypeName UserServiceImpl
 * @Description 用户业务接口的实现
 * @Project beetle
 * @since 1.0.0
 * @Author guojianxia
 * @Date 2016年1月8日 下午6:14:21
 */
@Service
public class UserServiceImpl  implements UserService {
	
	private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	//private static final String User = null;

	@Autowired
	private UserDao userDao;

	@Autowired
	private WebSessionManager sessionManager;

	@Override
	public PageBean<User> queryAllUser(Integer roleId, User user) {
		
		Integer currentPage = PagingContext.getPageNo();
		Integer pageSize = PagingContext.getPageSize();
		String username = user.getUsername();
		String realname = user.getRealname();
		Integer gender = user.getGender();
		String company = user.getCompany();
		Integer departmentId = user.getDepartmentId();
		Integer status = user.getStatus();
		// 设置查询对象
		UserQuery userQuery = new UserQuery();
		// 设置返回字段
		//String fields = "id,username,realname,status";
		//userQuery.setFields(fields);
		// 设置当前页
		userQuery.setPageNo(currentPage);
		// 设置每页条数
		userQuery.setPageSize(pageSize);
		// 创建查询条件
		Criteria createCriteria = userQuery.createCriteria();
		if (StringUtils.isNotBlank(username)) {
			createCriteria.andUsernameLike("%"+username+"%");
		}
		if (StringUtils.isNotBlank(realname)) {
			createCriteria.andRealnameLike("%"+realname+"%");
		}
		if (StringUtils.isNotBlank(company)) {
			createCriteria.andCompanyLike("%"+company+"%");
		}
		if (gender != null) {
			createCriteria.andGenderEqualTo(gender);
		}
		if (departmentId != null) {
			createCriteria.andDepartmentIdEqualTo(departmentId);
		}
		if (status != null) {
			createCriteria.andStatusEqualTo(status);
		}
		// 统计总记录数
		int count = userDao.countByExample(userQuery);
		// 设置分页对象
		PageBean<User> pageBean = new PageBean<User>(currentPage, pageSize, count, null);
		// 获得总页数
		int pageCount = pageBean.getPageCount();
		if (currentPage > pageCount&& pageCount > 0) {
			// 传递来的当前页大于总页数时，就将当前页设为总页数
			userQuery.setPageNo(pageCount);
		}
		// 查询出所有符合条件的用户
		List<User> list = userDao.selectByExample(userQuery);
		for (User u : list) {
			List<Integer> roleIds = userDao.queryRoleIdsByUserId(u.getId());
			u.setRoleIds(roleIds);
		}
		pageBean.setRecordList(list);
		// 返回分页对象
		return pageBean;// new PageBean(currentPage, pageSize, count, list);
	}

	@Transactional
	public Boolean addUser(User user, Integer[] roleIds) {
		Integer k = 0;
		// 查询当前传来的用户名是否存在
		String username = user.getUsername();
		UserQuery userQuery = new UserQuery();
		userQuery.createCriteria().andUsernameEqualTo(username);
		List<User> list = userDao.selectByExample(userQuery);
		// 如果用户名存在则失败
		if (list != null && list.size() > 0) {
			return false;
		} else {// 用户名如果不存在则进行添加
			if (user.getStatus() == null) {
				user.setStatus(1);
			}
			// 判断用户名、密码、真实姓名是否为空
			if (user.getUsername() != null && user.getRealname() != null && user.getPassword() != null) {
				// 添加一条用户数据
				k = userDao.insertSelective(user);
			} else {
				// 不符合条件则添加失败
				return false;
			}
			if (k != null && k > 0){
				return true;
			}else{
				return false;
			}
		}
	}

	@Transactional
	public Boolean updateUser(User user) {
		Integer i = userDao.updateByPrimaryKeySelective(user);
		if (i != null && i > 0){
			return true;
		}else{
			return false;
		}
	}

	

	@Transactional
	public Boolean updateUserStatus(Integer id, Integer status) throws DataException {
		Integer i = 0;
		// 先将用户的角色关系解除
		User user = userDao.selectByPrimaryKey(id);
		if(user.getUsername().equals("admin")){
			throw new DataException(Il8nUtil.getMessage("biz.UserServiceImpl.updateUserStatus.msg1"));
		}
		if (user != null) {
			// 判断是否传递了要修改的状态
			if (status == 0 || status == 1) {
				
				// 修改用户状态
				user.setStatus(status);
				i = userDao.updateByPrimaryKeySelective(user);
			}
		}
		if (i != null && i > 0){
			return true;
		}else{
			return false;
		}
	}


	/**
	 * 
	 * @Description  获得当前登录的用户
	 * @param request
	 * 
     * @return 返回登录的用户
	 */
    public  User getLoginUser(){
    	User user = null;
        try {
        	Session session = SecurityUtils.getSubject().getSession();
        	user = (User) session.getAttribute("loginUser");
		} catch (Exception e){ 
			logger.error("没有获取到后台登录用户！");
		}
        return user;
    }

	@Override
	public String getLoginUserName() {
		String userName = "";
		User loginUser = getLoginUser();
		if (loginUser == null) {
			userName = "未知用户";
		} else {
			userName = loginUser.getUsername();
		}
		return userName;
	}

	@Override
	public User getLoginUserBySessionId(String sessionId) throws DataException {
		// 1.sessionId为空不能获取
		if(StringUtils.isBlank(sessionId)){
			throw new ParameterEmptyException("sessionId为空不能获取登录用户！");
		}
		// 2.将sessionId转换为sessionKey获取会话及当中的用户
		User user = null;
		try {
			Session session = getSessionBySessionId(sessionId);
			user = (User)session.getAttribute("loginUser");
		} catch (Exception e) {
			logger.error("获取登录用户产生异常：{}",ExceptionUtil.getStackTrace(e));
			throw new DataException("获取登录用户异常！");
		}
		return user;
	}

	@Override
	public Session getSessionBySessionId(String oldSessionID) throws DataException {
		// 1.sessionId为空不能获取
		if(StringUtils.isBlank(oldSessionID)){
			throw new ParameterEmptyException("sessionId为空不能获取登录用户！");
		}
		// 2.将sessionId转换为sessionKey获取会话
		Session session = null;
		try {
			DefaultSessionKey sessionKey = new DefaultSessionKey(oldSessionID);
			session = sessionManager.getSession(sessionKey);
		} catch (Exception e) {
			logger.error("获取登录用户产生异常：{}",ExceptionUtil.getStackTrace(e));
			throw new DataException("获取登录用户异常！");
		}
		return session;
	}

	@Override
	public Map<String, String> getUserForShow(User user) {
		UserQuery example = new UserQuery();
		String userName = user.getUsername();
		String[] names = userName.split(",");
		Set<String> set = new HashSet<String>();
		for(String str : names){
			set.add(str);
		}
		List<String> lst = new ArrayList<String>(set);
		example.createCriteria().andUsernameIn(lst);
		List<User> userList = userDao.selectByExample(example);
		Map<String,String> map = new HashMap<String, String>();
		for(User u : userList){
			map.put(u.getUsername(), u.getRealname());
		}
		return map;
	}

	@Override
	public List<User> list(User user) {
		UserQuery example = new UserQuery();
		UserQuery.Criteria c = example.createCriteria();
		c.andStatusEqualTo(1);
		if(user != null){
			if(StringUtils.isNotBlank(user.getUsername())){
				c.andUsernameLike(user.getUsername());
				example.or(example.createCriteria().andStatusEqualTo(1).andRealnameLike(user.getUsername()));
			}
		}
		return userDao.selectByExample(example);
	}

}
